import { Icon } from "@/components/icon";
import type { ColumnsType } from "antd/es/table";
import { Button } from "antd";
import { ScrollArea } from "@/ui/scroll-area";
import { userList } from "@/api/services/sysService";
import { useState, useMemo, useEffect, useRef } from "react";
import type { OnRowType } from "@/components/ProTable/Index";
import { ProModal, ProTable, ProForm } from "@/components";
import type { FormItem } from "@/components/ProForm/Index";
import dayjs from "dayjs";
// import type { UploadFile } from 'antd';
import type { SearchFormItem } from "@/components/ProTable/Index";
// 表格数据类型
interface DataType {
	userId: string;
	username: string;
	email: string;
	createTime: string;
	status: number;
}

// 表单项类型
type FormValues = {
	username: string;
	email: string;
	status?: number;
	startDate?: string;
	endDate?: string;
	resizable?: boolean;
};

// 表格页面
const TablePage = () => {
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [statusDict, setStatusDict] = useState<any[]>([]);
	const [editRecord, setEditRecord] = useState<DataType | null>(null);
	const modalRef = useRef<any>(null);
	const formRef = useRef<any>(null);
	// 表格列配置
	const columns: ColumnsType<DataType> = [
		{
			title: "ID",
			dataIndex: "userId",
			key: "userId",
			fixed: "left",
		},
		{
			title: "用户名",
			dataIndex: "username",
			key: "username",
			sorter: true,
			filters: [
				{
					text: "Joe",
					value: "Joe",
				},
				{
					text: "Category 1",
					value: "Category 1",
					children: [
						{
							text: "Yellow",
							value: "Yellow",
						},
						{
							text: "Pink",
							value: "Pink",
						},
					],
				},
				{
					text: "Category 2",
					value: "Category 2",
					children: [
						{
							text: "Green",
							value: "Green",
						},
						{
							text: "Black",
							value: "Black",
						},
					],
				},
			],
			filterMode: "tree",
			filterSearch: true,
			onFilter: (value, record) => record.username.includes(value as string),
		},
		{
			title: "邮箱",
			dataIndex: "email",
			key: "email",
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			render: (_, record) => (record.status === 1 ? "启用" : "禁用"),
		},
		{
			title: "注册时间",
			key: "createTime",
			dataIndex: "createTime",
			// width: 150,
		},
		{
			title: "Action",
			key: "action",
			width: 180,
			fixed: "right",
			render: (_, record) => (
				<div>
					<Button className="mr-2" color="primary" variant="outlined" size="small" onClick={() => editHandler(record)}>
						<Icon icon="mdi:edit" />
						编辑
					</Button>
					<Button color="danger" variant="outlined" size="small">
						<Icon icon="mdi:delete" />
						删除
					</Button>
				</div>
			),
		},
	];

	// 搜索表单
	const searchForm = useMemo<SearchFormItem[]>(() => {
		return [
			{
				name: "username",
				label: "用户名",
				type: "input",
			},
			{
				name: "createTime",
				label: "注册时间",
				type: "dateRange",
				format: "YYYY-MM-DD",
				rangeName: ["startDate", "endDate"],
				isDateRange: true,
				initialValue: [dayjs().subtract(12, "month"), dayjs()],
			},
			{
				name: "email",
				label: "邮箱",
				type: "input",
			},
			{
				name: "status",
				label: "状态",
				type: "select",
				options: statusDict,
			},
		];
	}, [statusDict]);

	// 新增、修改表单项
	const formItems = useMemo<FormItem[]>(() => {
		return [
			{
				name: "username",
				label: "用户名",
				type: "input",
				onChange: (e: any) => {
					console.log(e.target.value);
				},
				rules: [{ required: true, message: "请输入用户名" }],
			},
			{
				name: "email",
				label: "邮箱",
				type: "input",
				rules: [{ required: true, message: "请输入邮箱" }],
			},
			{
				name: "status",
				label: "状态",
				type: "select",
				options: [
					{ label: "启用", value: 1 },
					{ label: "禁用", value: 0 },
				],
				rules: [{ required: true, message: "请选择状态" }],
			},
			{
				name: "createTime",
				label: "注册时间",
				type: "date",
				format: "YYYY-MM-DD",
			},
			{
				name: "createTime2",
				label: "注册时间2",
				type: "date",
				isDateRange: true,
				format: "YYYY-MM-DD",
				rangeName: ["startDate", "endDate"],
				// initialValue: [dayjs().subtract(12, 'month'), dayjs()],
			},
			{
				name: "checkbox",
				label: "复选框",
				type: "checkbox",
				options: [
					{ label: "选项1", value: 1 },
					{ label: "选项2", value: 2 },
					{ label: "选项3", value: 3 },
				],
			},
			{
				name: "inputNumber",
				label: "数字输入框",
				type: "inputNumber",
			},
			{
				name: "radio",
				label: "单选框",
				type: "radio",
				options: [
					{ label: "选项1", value: 1 },
					{ label: "选项2", value: 2 },
					{ label: "选项3", value: 3 },
				],
			},
			{
				name: "switch",
				label: "开关",
				type: "switch",
			},
			{
				name: "treeSelect",
				label: "树选择器",
				type: "treeSelect",
				treeCheckable: true,
				onChange: (value: any, label: any, extra: any) => {
					console.log(value, label, extra);
				},
				treeData: [
					{
						value: "1",
						title: "选项1",
						children: [{ value: "1-1", title: "选项1-1" }],
					},
					{
						value: "2",
						title: "选项2",
						children: [{ value: "2-1", title: "选项2-1" }],
					},
				],
			},
			{
				name: "upload",
				label: "上传",
				type: "upload",
				onChange: (file) => {
					console.log(file);
				},
				listType: "picture-card",
				previewImage: true,
				fileType: ["image/png", "image/jpg", "image/jpeg"],
				maxFileSize: 2,
				maxCount: 2,
			},
		];
	}, [editRecord]);

	// 监听 editRecord 变化，自动回填表单
	useEffect(() => {
		console.log("editRecord", editRecord);
		formRef.current?.setFromFieldsValue({
			username: editRecord?.username,
			email: editRecord?.email,
			status: 1,
			createTime: [dayjs().subtract(12, "month"), dayjs()],
			checkbox: [1, 2],
			upload: [
				{
					uid: "-1",
					name: "image.png",
					status: "done",
					url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
				},
			],
		});
	}, [editRecord]);

	// 模拟接口请求，在useEffect, 在useEffect中请求接口，并设置状态，不然会有副作用
	useEffect(() => {
		const timer = setTimeout(() => {
			setStatusDict([
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 },
			]);
		}, 2000);

		return () => clearTimeout(timer);
	}, []);

	// 编辑
	const editHandler = (record: DataType) => {
		modalRef.current?.openModal();
		setEditRecord(record);
	};
	// 关闭模态框
	const closeModal = () => {
		modalRef.current?.closeModal();
		setEditRecord(null);
	};

	// 回调函数
	const callback = ({ selectedRowKeys }: { selectedRowKeys: React.Key[] }) => {
		setSelectedRowKeys(selectedRowKeys);
	};

	// 展开行配置
	const expandable = {
		expandedRowRender: (record: any) => <p style={{ margin: 0 }}>{record.password}</p>,
		rowExpandable: (record: any) => record.name !== "Not Expandable",
	};

	// 行事件
	const onRow = (record: DataType, index: number) => {
		return {
			onClick: () => {
				// 点击事件
				console.log(record, index);
			},
			onDoubleClick: () => {
				// 双击事件
				console.log(record, index);
			},
		};
	};

	// 表格头部右侧插槽
	const tableHeaderRightSlot = (
		<div className="flex gap-2">
			<Button
				type="primary"
				onClick={() => {
					formRef.current?.resetForm?.();
					modalRef.current?.openModal();
					setEditRecord(null);
				}}
			>
				<Icon icon="mdi:add" />
				新增
			</Button>
			<Button type="primary" disabled={selectedRowKeys.length === 0} danger>
				<Icon icon="mdi:delete" />
				批量删除
			</Button>
		</div>
	);

	// 表单提交
	const onFinish = (values: FormValues) => {
		console.log(values);
	};

	return (
		<div>
			<ScrollArea>
				<ProTable<DataType>
					title="用户列表"
					searchForm={searchForm}
					tableHeaderRightSlot={tableHeaderRightSlot}
					callback={callback}
					columns={columns}
					api={userList}
					isRowSelection
					isShowCustom
					rowKey={(record) => record.userId}
					expandable={expandable}
					onRow={onRow as OnRowType<DataType>}
				/>
			</ScrollArea>
			{/* 新增 */}
			<ProModal ref={modalRef} title="新增">
				<ProForm<FormValues> formItems={formItems} ref={formRef} onFinish={onFinish} closeModal={closeModal} />
			</ProModal>
		</div>
	);
};

export default TablePage;
